<template>
  <view class="showpage">
    <!-- <u-navbar bgColor='#4871C0' :titleStyle="{ color: '#FFF'}" title="会议室详情" leftIconColor="#FFF"
               @leftClick="leftClick" @rightClick="rightClick" :autoBack="true">

       <view class="navbar-right" slot="right">
         <img src="../../../../static/assets/images/draft_pic.png"/>
       </view>
     </u-navbar>
     -->
    <div class="room"  >
      <div class='roomTitle'>
				<span class='small'
              :style="info.room_type ==1 ?'background: #fc5531;':''">{{ info.room_type == "1" ? '临时' : '固定' }}</span>
        {{ info.edifice ? info.edifice.name : '' }}
        <p>{{ info.title }}{{ info.floor }} {{ info.number }}</p>
        <p>{{ info.time_scope }} I {{ info.people }}人</p>
        <p>管理员:{{ info.user ? info.user.nickname : info.manager_name }}</p>

      </div>
    </div>
    <div class="form">
      <view class="tab-box">
        <u-tabs :list="list1" :scrollable="false" lineColor="#4871C0" :current="activeIndex" @change="changeTab"
                lineWidth="70rpx" lineHeight="5rpx" :activeStyle="{
				    color: '#4871C0',
				    fontWeight: 'bold',
					fontSize:'28rpx',
				}" :inactiveStyle="{
				    color: '#999999',
					fontSize:'28rpx',
				}" itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;width:30%;padding-bottom:10rpx;"></u-tabs>
      </view>
      <!-- <u-tabs :list="list1" ></u-tabs> -->

      <div class="times">
        <div class="swiper-container">
          <div class="swiper-wrapper">
            <div class="swiper-slide" v-for="(v, i) in info.res" :key="i">
              <p class="timeList">
                <span class="timeNum">{{ i }}:00</span>
                <span v-for="(val, index) in v" :key="index" class="linBg"
                      @click="onTimeClick(val, i, index)"
                      :style="val.sel ?'background-color: #FF7A00;':''"
                      :class="val.state.code== 0? 'state0':(val.state.code==1? 'state1':(val.state.code==2? 'state2':(val.state.code==3? 'state3':'state4')))">
								</span>
              </p>
            </div>
          </div>
        </div>
      </div>

      <p class='hit'>注：每个小块15分钟，点击相应色块可以进行预约！</p>
      <div class="subButton" @click="openPop">
        预定会议室
      </div>
    </div>


    <u-popup :show="show" mode="bottom" @close="closePop" @open="openPop" :closeable="true" :border-radius="10"
             close-icon-color="#010101" :mask-close-able="false" close-icon-size="42">
      <view class="content" style="height:60%">
        <!-- <u-icon name="checkbox-mark" color="#4871C0" size="28"></u-icon> -->
        <view class="title">请选择会议类型</view>

        <view @click="selType(v)" :class="typeId.id==v.id?'meet active':'meet '" v-for="(v, i) in typeList">
          {{ v.title }}
          <text>
            <img src="@/static/assets/images/dui.png" v-if="typeId.id==v.id"/></text>
        </view>

        <view class='meethit'>党总支会议、校长办公会议、行政办公会、全体职工会议，仅有限定人员可以发起！</view>
        <view class="btn">
          <u-button class='cancelbtn' @click="closePop">取消</u-button>
          <u-button type="primary" text="确定" @click="submit" color='#4871C0'></u-button>
        </view>
      </view>
    </u-popup>

    <picker ref="picktime1" mode="date" :value="date" :start="startDate" @change="bindDateChange">

    </picker>
  </view>
</template>

<script>
import Swiper from "@/static/assets/js/swiper.min.js";
import {
  getMeetTypesList,
  getRoomList,
  getRoomDetail,
  checkRoom
} from '@/api/roomApi.js'

export default {
  data() {
    var date = this.format("yyyy-mm-dd");
    var d = new Date();
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    var day = d.getDate();

    return {
      show: false,
      typeList: [],
      typeId: {},
      activeIndex: 0,
      startDate: new Date(),
      list1: [{
        name: '今天',
      }, {
        name: '明天',
      }, {
        name: '后天'
      }, {
        name: '自定日期',

      }],
      id: 1,
      info: {},
      order: {
        push: [],
        date: date,
        hour: 1,
      },
      today: "",
      timeText: "",
      start_time: "",
      end_time: "",
      times: [],
      times0: [],
      selectTimes: [],
      allTimes: [],
      selectItem: [],
      selectPopup: false,
      year: year,
      month: month,
      day: day,
      date: date,
      date1: date,
      date2: date,
      timesTemp: [],
    };
  },

  onShow: function () {
    const {
      id,
      year,
      month,
      day
    } = this.$route.query;
    this.id = id || 1;
    this.year = year;
    this.month = month;
    this.day = day;
    this.getToday();
    const d = new Date(this.year + "/" + this.month + "/" + this.day);
    this.date = this.format("yyyy-mm-dd", d);
    if (this.date != this.today) {
      //this.changeTab({index:3});
      this.activeIndex = 3;
    } else {
      this.activeIndex = 0;
    }

    this.date1 = this.dateAdd(this.today, 1);
    this.date2 = this.dateAdd(this.today, 2);
    this.week = d.getDay();
    this.getRoomInfo();
    this.getMeetTypes();
  },
  watch: {
    times: {
      handler(newVal, oldVal) {
        /*
    *
        if (newVal.length == 0) {
          this.timeText = "";
        }
        if (newVal.length == 1) {
          this.timeText = this.format("hh:ii开始", newVal[0]);
          this.start_time = this.date + " " + this.format("hh:ii", newVal[0]);
        }
        if (newVal.length == 2) {
          let end = newVal[1].setMinutes(newVal[1].getMinutes() + 15);
          this.timeText =
            this.format("hh:ii开始", newVal[0]) +
            this.format("hh:ii前结束", new Date(end));
          this.start_time = this.date + " " + this.format("hh:ii", newVal[0]);
          this.end_time = this.date + " " + this.format("hh:ii", new Date(end));

        }
        * */
      },
      deep: true,
    },
    selectTimesChange: {
      handler(newVal, oldVal) {
        /*
    *
        if (newVal.length == 0) {
          this.getRoomInfo();
        }

        if (newVal.length == 1) {
         this.times0 = newVal[0];
          if (oldVal[0]) {
            this.info.res[oldVal[0].hour][oldVal[0].step]['sel'] =false ;
          }
          this.info.res[newVal[0].hour][newVal[0].step]['sel'] = false;
        }

        if (newVal.length == 2) {
            if (JSON.stringify(newVal[1])  == JSON.stringify(oldVal[1])  ) {
           if (JSON.stringify(newVal[1])   == JSON.stringify(this.times0)) {
            this.times = [];
            this.times0 = [];
           this.selectTimes = [];
           //this.getRoomInfo();
           }}

          let setStatus = function(data, status, self) {
            for (let i in self.info.res) {
              for (let step in self.info.res[i]) {
                let start = data[0].hour * 60 + data[0].step * 15;
                let end = data[1].hour * 60 + data[1].step * 15;
                let time = i * 60 + step * 15;
              //	if (time >= start && time <= end) {

                  var aa = self.info.res[i][step];
                  aa.sel = status;
                  self.$set(self.info.res[i], step, aa);
              //	}
              }
            }
          };
          // 将旧选择数据改为开启状态
          if (oldVal[0] && !oldVal[1]) {
            this.info.res[oldVal[0].hour][oldVal[0].step]['sel'] = false;
          } else {
            setStatus(oldVal, false, this);
          }
          // 修改为关闭状态
          setStatus(newVal, true, this);
        }
*/
      },
      deep: true,
    },
  },
  computed: {
    selectTimesChange() {
      return JSON.parse(JSON.stringify(this.selectTimes));
    },
  },
  updated: function () {
    const swiper = new Swiper(".swiper-container", {
      slidesPerView: 7,
      spaceBetween: 15,
      freeMode: true,
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
    });
  },
  methods: {

    leftClick() {
      uni.switchTab({
        url: '/pages/tabbar/meeting-room/meeting-room'
      })
    },
    openPop() {
      this.show = true;
    },
    closePop() {
      this.show = false;
    },
    dateAdd(startDate, num) {
      startDate = new Date(startDate);
      startDate = +startDate + 1000 * 60 * 60 * 24 * num;
      startDate = new Date(startDate);

      var month = (startDate.getMonth() + 1);
      // 变成两位
      month = month < 10 ? '0' + month : month;
      // 获取日
      var day = startDate.getDate();
      day = day < 10 ? '0' + day : day;
      var nextStartDate = startDate.getFullYear() + "-" + month + "-" + day;

      return nextStartDate;
    },
    getToday() {
      var d = new Date();
      // 获取年，getFullYear()返回4位的数字
      var year = d.getFullYear();
      // 获取月，月份比较特殊，0是1月，11是12月
      var month = d.getMonth() + 1;
      // 变成两位
      month = month < 10 ? '0' + month : month;
      // 获取日
      var day = d.getDate();
      day = day < 10 ? '0' + day : day;
      this.today = (year + '-' + month + '-' + day);
    },
    callPicker() {
      this.$refs.picktime1.$el.click()
    },

    bindDateChange: function (e) {
      this.date = e.detail.value;
      if (this.date == this.today) {
        this.activeIndex = 0;
      } else if (this.date == this.date1) {
        this.activeIndex = 1;
      } else if (this.date == this.date2) {
        this.activeIndex = 2;
      }
      this.getRoomInfo();
    },
    changeTab(item) {
      console.log(this.activeIndex)
      console.log(item)
      this.activeIndex = item.index;

      if (item.index == 0) {
        this.date = this.today;// this.$route.query.year + "-" + this.$route.query.month + "-" + this.$route.query.day;
      } else if (item.index == 1) {
        this.date = this.date1;
      } else if (item.index == 2) {
        this.date = this.date2;
      } else {
        this.callPicker();
      }
      this.times = [];
      this.selectTimes = [];
      this.getRoomInfo();

    },
    selType(item) {
      this.typeId = item;
      uni.setStorageSync('type_id', item.id);
    },
    onTimeClick(item, hour, step) {
      console.log("onTimeClick:", item)
      console.log("hour:", hour)
      console.log("index:", step)

      // 关闭状态
      let minutes = [0, 15, 30, 45];
      let _hour = hour > 9 ? hour : "0" + hour;
      let date = new Date(
          this.date.replace(/\-/g, "/") +
          " " +
          _hour +
          ":" +
          minutes[step] +
          ":00"
      );
      date = this.format("yyyy-mm-dd hh:ii:ss", date)


      if (!this.times[0]) {
        this.$set(this.selectItem, 0, item);
        this.$set(this.times, 0, date);
        this.$set(this.selectTimes, 0, {
          hour: hour,
          step: step
        });
        this.$set(this.selectItem, 1, item);
        this.$set(this.times, 1, date);
        this.$set(this.selectTimes, 1, {
          hour: hour,
          step: step
        });
      } else {

        //假如时间是alltimes 的最后一个，证明再次点击了同样的，那么直接等于上一个，

        console.log("======最后一个：：>",this.allTimes[this.allTimes.length-1].start_time,date)
        console.log("======最后一个：：>",this.allTimes[this.allTimes.length-1].start_time,this.allTimes[this.allTimes.length-1].end_time,date)
        //选择时间小于当前时间，置灰
        if(this.allTimes.length > 1) {
          if (Number(new Date(this.allTimes[this.allTimes.length - 1].start_time)) == Number(new Date(date))) {
            date = this.allTimes[this.allTimes.length - 2].start_time;
            item = this.allTimes[this.allTimes.length - 2];
          }
        }


        this.times0 = date;
        this.$set(this.selectItem, 1, item);
        this.$set(this.times, 1, date);
        this.$set(this.selectTimes, 1, {
          hour: hour,
          step: step
        });
      }

      console.log("this.times===>>>", this.times, this.times0)

      if ((this.times[1] < this.times[0])) {
        let tmp = this.times;
        let tmpSel = this.selectTimes;
        let selectItem = this.selectItem;
        console.log("tmp===>>>", tmp)
        console.log("tmpSel===>>>", tmpSel)
        this.times = [tmp[1], tmp[0]]
        this.selectTimes = [tmpSel[1], tmpSel[0]]
        this.selectItem = [selectItem[1], selectItem[0]]
      }

      this.timeText = this.selectItem[0].start_time + this.selectItem[1].end_time;
      this.start_time = this.selectItem[0].start_time;
      this.end_time = this.selectItem[1].end_time;


      if(this.times[0] == this.times[1]) {
        if(this.allTimes.length > 0) {
          if ((Number(new Date(this.times[0])) == Number(new Date(this.allTimes[this.allTimes.length - 1].start_time)))) {
            this.times = [];
            this.times0 = "";
            this.start_time = "";
            this.end_time = "";
          }
        }
      }

      for (let i in this.info.res) {
        for (let step in this.info.res[i]) {
          var aa = this.info.res[i][step];
          if ((Number(new Date(aa.start_time)) >= Number(new Date(this.start_time))) && (Number(new Date(aa.end_time)) <= Number(new Date(this.end_time)))) {
            if (aa.state.code != 1) {
              this.times = [];
              this.times0 = "";
              this.start_time = "";
              this.end_time = "";
              this.$toast("请选择可用的会议时间");
              break;
            }
          }
        }
      }

      this.allTimes = [];
      for (let i in this.info.res) {
        for (let step in this.info.res[i]) {
          var aa = this.info.res[i][step];
          if ((Number(new Date(aa.start_time)) >= Number(new Date(this.start_time))) && (Number(new Date(aa.end_time)) <= Number(new Date(this.end_time)))) {
            aa.sel = true;
            this.info.res[i][step].sel = true;
            this.allTimes.push(aa);
            // this.$set(this.info.res[i], step, aa);
          } else {
            aa.sel = false;
            this.info.res[i][step].sel = false;
            //this.$set(this.info.res[i], step, aa);
          }
        }
      }

      console.log("this.allTimes====>>>>",this.allTimes);

    },
    cancel() {
      this.times = [];
      this.selectTimes = [];
      this.getRoomInfo();
    },

    getMeetTypes() {
      const _this = this;
      getMeetTypesList({}).then(res => {
        console.log(res)
        _this.typeList = res.data
      })
    },
    getRoomInfo() {
      let params = {};
      params.id = this.id;
      params.day = this.day;
      params.month = this.month;
      params.year = this.year;
      params.date = this.date;
      const _this = this;

      getRoomDetail(params).then(res => {
        console.log(res)
        _this.info = res.data;
        //   _this.info.times = res.data.res;
        //   _this.$indicator.close();
      })
    },
    openPicker() {
      this.cancel();
      this.$refs.picker.open();
    },
    selectDate(date) {
      this.order.date = this.format("yyyy-mm-dd", date);
      this.year = date.getFullYear();
      this.month = date.getMonth() + 1;
      this.day = date.getDate();
      this.week = date.getDay();
      this.getRoomInfo();
    },
    format(format, date) {
      if (!date) {
        date = new Date();
      }
      var o = {
        "m+": date.getMonth() + 1, //month
        "d+": date.getDate(), //day
        "h+": date.getHours(), //hour
        "i+": date.getMinutes(), //minute
        "s+": date.getSeconds(), //second
        "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
        S: date.getMilliseconds(), //millisecond
      };
      if (/(y+)/.test(format)) {
        format = format.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(
              RegExp.$1,
              RegExp.$1.length == 1 ?
                  o[k] :
                  ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }
      return format;
    },
    submit() {
      this.closePop();
      if (!this.end_time) {
        this.$toast("请选择会议时间");
        return false;
      }
      if (!uni.getStorageSync('type_id')) {
        this.$toast("请输入会议类型");
        return false;
      }

      uni.setStorageSync('start_time', this.start_time);
      uni.setStorageSync('end_time', this.end_time);
      uni.setStorageSync('room_id', this.id);
      uni.setStorageSync('room_info', this.info);

      const url =
          "/pages/tabbar/meeting-room/add/newPartyConference?id=" +
          this.id +
          "&start_time=" +
          this.start_time +
          "&end_time=" +
          this.end_time +
          "&type_id=" +
          uni.getStorageSync('type_id');

      let params = {};
      params.room_id = this.id;
      params.start_time = this.start_time;
      params.end_time = this.end_time;
      checkRoom(params).then(res => {
        if (res.code == 1) {

          uni.navigateTo({
            url,
          });

        } else {
          this.$toast(res.msg);
        }
      })


    },
    post() {
      if (!this.order.title) {
        this.$toast("请输入会议主题");
        return false;
      }
      if (!this.order.date) {
        this.$toast("请输入会议日期");
        return false;
      }
      if (!this.times[0] || !this.times[1]) {
        this.$toast("请选择会议时间");
        return false;
      }
      if (!this.order.people) {
        this.$toast("请输入参会人数");
        return false;
      }
      if (!this.order.hour) {
        this.$toast("会议时长不能为空");
        return false;
      }
      if (this.order.people > this.info.people) {
        this.$toast("超过房间最大容纳人数");
        return false;
      }
      var params = new URLSearchParams();
      params.append("room_id", this.info.id);
      params.append("title", this.order.title);
      params.append("date", this.format("yyyy-mm-dd hh:ii:ss", this.times[0]));

      params.append("people", this.order.people);
      params.append("contact", this.order.contact);
      params.append("token", token);
      var dateDiff = this.times[1].getTime() - this.times[0].getTime(); //时间差的毫秒数
      var hours = dateDiff / (3600 * 1000); //计算出小时数
      params.append("hour", hours);

      var _this = this;
      this.$axios
          .post(_this.$rootUri + "/api/orderCreate", params)
          .then(function (res) {
            if (res.status == 200) {
              if (res.data.code == 1) {
                _this.$messagebox.alert("提交成功").then(function () {
                  window.location.href = _this.$rootUri + "/meeting.html";
                });
              } else if (res.data.code == -1) {
                _this.$toast(res.data.msg);
                // 时段被占用，重新刷新数据
                _this.times = [];
                _this.selectTimes = [];
                _this.getRoomInfo();
              } else {
                _this.$toast(res.data.msg);
              }
            } else {
              _this.$toast("提交失败");
            }
          });
    },
    select() {
      var _this = this;
      if (_this.users.length > 1) {
        _this.selectPopup = true;
        return false;
      }
      _this.$indicator.open("获取中...");
      _this.$axios
          .get(_this.$rootUri + "/wechat/users")
          .then(function (res) {
            if (res.status == 200 && res.data.code == 1) {
              var users = [];
              for (var i in res.data.data) {
                users.push({
                  label: res.data.data[i].name,
                  value: res.data.data[i].userid,
                });
              }
              _this.users = users;
              _this.$indicator.close();
              _this.selectPopup = true;
            } else {
              _this.$indicator.close();
            }
          })
          .catch(function (error) {
            console.error(error);
            _this.$indicator.close();
          });
    },
    selectClose() {
      this.selectPopup = false;
      this.order.people = this.order.users.length;
    },
  },
};
</script>

<style>
@import "@/static/assets/css/index.css";
@import "@/static/assets/css/mobiscroll.core-2.5.2.css";
@import "@/static/assets/css/mobiscroll.animation-2.5.2.css";
@import "@/static/assets/css/mobiscroll.android-ics-2.5.2.css";

@import "@/static/assets/css/swiper.min.css";
@import "@/static/assets/css/show.css";

.navbar-right {
  width: 30px;
}

.navbar-right img {
  width: 100%;
  height: auto;
}

.subButton {
  z-index: 1000;
}

.timeList .state0 {
}

.timeList .state1 {
  background: #F1F6FF;
}

.timeList .state2 {
  background: #B2CFFF;
}

.timeList .state3 {
  background: #B2CFFF;
}
</style>
